﻿#include "shellaudio.h"
#include <QAudio>
#include <QAudioFormat>
#include <QMediaDevices>
#include <QAudioDevice>
#include <QtConcurrent>
#include "../ConfigDef.h"

extern "C"{
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libavdevice/avdevice.h>
#include <libavutil/opt.h>
#include <libswresample/swresample.h>
}

// 定义注册表的路径和键
// const QString REGISTRY_PATH = "HKEY_CURRENT_USER\\Software\\Hushan\\NetcastClient";
// const QString CLIENT_ID_KEY = "ClientId";

QScopedPointer<ShellAudio> ShellAudio::instance;

void ShellAudio::init()
{
    avdevice_register_all();
    QSettings setting(CONFIG_FILE,QSettings::IniFormat);
    if(setting.contains("SaveLocalRecord")){
        if(setting.value("SaveLocalRecord").toBool()){
            QDir dir;
            if(!dir.exists("record")){
                dir.mkdir("record");
            }
        }
    }else{
        setting.setValue("SaveLocalRecord",false);
    }
}

void ShellAudio::initClientId()
{


}


QVariantList ShellAudio::getAudioInputDevices()
{
    QAudioFormat format;    
    format.setSampleRate(44100);
    format.setChannelConfig(QAudioFormat::ChannelConfigStereo);
    format.setChannelCount(2);
    format.setSampleFormat(QAudioFormat::Int16);
    QVariantList devices;
    for(auto& it:  QMediaDevices::audioInputs()) {
        if(it.isFormatSupported(format)){
            // qDebug()<<it.id()<<it.description()<<it.mode()<<it.isDefault();
            devices<<it.description();
        }
    }
    _audioInputDevices = devices;
    return _audioInputDevices;
}

void ShellAudio::createAudioRecord(QString taskId,int sessionId, QString device, int bitrate, MediaPlayer::CH_MODE chMode)
{
    MediaPlayer * mediaPlayer = _mediaPlayerMap.value(taskId);
    if(mediaPlayer == nullptr){
        mediaPlayer = new MediaPlayer(taskId,sessionId,device,bitrate,chMode,_useFFmpeg);
        _mediaPlayerMap.insert(taskId,mediaPlayer);
        connect(mediaPlayer,&MediaPlayer::sigFinished,this,[mediaPlayer,taskId, this](){
            _mediaPlayerMap.remove(taskId);
            delete mediaPlayer;
        });
        connect(mediaPlayer,&MediaPlayer::playerStateChanged,this,&ShellAudio::playerStateChanged);
    }
    mediaPlayer->start();
}

void ShellAudio::startAudioRecord(QString taskId)
{
    auto mediaPlayer = _mediaPlayerMap.value(taskId);
    if(mediaPlayer)
        mediaPlayer->start();
}

void ShellAudio::stopAudioRecord(QString taskId)
{
    auto mediaPlayer = _mediaPlayerMap.value(taskId);
    if(mediaPlayer){
        mediaPlayer->stop();
    }
}

void ShellAudio::pauseAudioRecord(QString taskId)
{
    auto mediaPlayer = _mediaPlayerMap.value(taskId);
    if(mediaPlayer)
        mediaPlayer->pause();
}

void ShellAudio::stopAll()
{
    for(auto player:std::as_const(_mediaPlayerMap)){
       player->stop();
    }
}

void ShellAudio::addLocalTask(QString userName, QString taskId)
{
    QSettings settings(LOCAL_TASK_FILE,QSettings::IniFormat);
    QVariantList list = settings.value(userName).toList();
    if(!list.contains(taskId)){
        list.append(taskId);
        settings.setValue(userName,list);
    }
}

QVariantList ShellAudio::getLocalTask(QString userName)
{
    QSettings settings(LOCAL_TASK_FILE,QSettings::IniFormat);
    return settings.value(userName).toList();
}

QString ShellAudio::getClientId()
{
    QSettings settings(REGISTRY_PATH, QSettings::NativeFormat);
    // 检查注册表中是否已存在唯一标识符
    QString clientId = settings.value(CLIENT_ID_KEY).toString();
    if (clientId.isEmpty()) {
        // 如果不存在，生成新的唯一标识符
        clientId = QUuid::createUuid().toString(QUuid::WithoutBraces);

        // 写入注册表
        settings.setValue(CLIENT_ID_KEY, clientId);
        settings.sync(); // 确保写入生效
        qDebug() << "Generated and saved new Unique ID:" << clientId;
    } else {
        qDebug() << "Read existing Unique ID from registry:" << clientId;
    }
    return clientId;
}

void ShellAudio::setUseFFmpeg(bool useFFmpeg)
{
    _useFFmpeg = useFFmpeg;
}

bool ShellAudio::getUseFFmpeg()
{
    return _useFFmpeg;
}






